package com.lening.common.util;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.net.URL;
import java.security.SecureRandom;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@Slf4j
public class OssUtil implements InitializingBean {

    //    读取配置文件内容

    @Value("oss-cn-beijing.aliyuncs.com")
    private String endpoint;

    @Value("LTAI5t6tUUC91j79krZqRJM4")
    private String accessKeyId;

    @Value("A7fTZEW4ODwlusIjj3NhtJmgrD4Bjc")
    private String accessKeySecret;

    @Value("p-picture")
    private String bucketName;

    public static String END_POINT;

    public static String ACCESS_KEY_ID;

    public static String ACCESS_KEY_SECRET;

    public static String BUCKET_NAME;

    @Override
    public void afterPropertiesSet() throws Exception{
        END_POINT = endpoint;

        ACCESS_KEY_ID = accessKeyId;

        ACCESS_KEY_SECRET = accessKeySecret;

        BUCKET_NAME = bucketName;
    }

    public static String uploadFileAvatar(MultipartFile multipartFile) {


        /*地域节点*/
        String endpoint = OssUtil.END_POINT;
        /*用户身份ID*/
        String accessKeyId = OssUtil.ACCESS_KEY_ID;
        /*与用户身份ID配对的密钥*/
        String accessKeySecret = OssUtil.ACCESS_KEY_SECRET;
        /*存储库名*/
        String bucketName = OssUtil.BUCKET_NAME;
        /*创建OSSClient实例*/
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        // 获取文件名
        String fileName = multipartFile.getOriginalFilename();
        log.info("阿里云OSS的文件fileName:{}", fileName);

        // 获取文件后缀名
        assert fileName != null;
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        log.info("阿里云OSS的文件suffixName:{}", suffixName);

        // 最后上传生成的文件名
        String finalFileName = System.currentTimeMillis() + "" + new SecureRandom().nextInt(0x0400) + suffixName;
        log.info("阿里云OSS的文件finalFileName:{}", finalFileName);

        // oss中的文件夹名
        String objectName = sdf.format(new Date()) + "/" + finalFileName;
        log.info("阿里云OSS的文件objectName:{}", objectName);

        // 文件上传
        try {
            ossClient.putObject(bucketName, objectName, new ByteArrayInputStream(multipartFile.getBytes()));
            //失效时间
            Date expiration = new Date(System.currentTimeMillis() + 3600 * 1000L);
            String url = ossClient.generatePresignedUrl(bucketName, objectName, expiration).toString();
            ossClient.shutdown();
            log.info("阿里云OSS的文件url:{}", url);

            return url;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public List<String> uploadArrayFileAvatar(MultipartFile[] multipartFiles) {

        /*地域节点*/
        String endpoint = OssUtil.END_POINT;
        /*用户身份ID*/
        String accessKeyId = OssUtil.ACCESS_KEY_ID;
        /*与用户身份ID配对的密钥*/
        String accessKeySecret = OssUtil.ACCESS_KEY_SECRET;
        /*存储库名*/
        String bucketName = OssUtil.BUCKET_NAME;
        /*创建OSSClient实例*/
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        List<String> list = new ArrayList<>();

        for (MultipartFile file : multipartFiles) {


            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");

            // 获取文件名
            String fileName = file.getOriginalFilename();

            // 获取文件后缀名
            assert fileName != null;
            String suffixName = fileName.substring(fileName.lastIndexOf("."));

            // 最后上传生成的文件名
            String finalFileName = System.currentTimeMillis() + "" + new SecureRandom().nextInt(0x0400) + suffixName;

            // oss中的文件夹名
            String objectName = sdf.format(new Date()) + "/" + finalFileName;
            // 文件上传
            try {
                ossClient.putObject(bucketName, objectName, new ByteArrayInputStream(file.getBytes()));
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            Date expiration = new Date(System.currentTimeMillis() + 3600 * 1000L);
            String url = ossClient.generatePresignedUrl(bucketName, objectName, expiration).toString();
            log.info("阿里云OSS的文件url:{}", url);
            list.add(url);
        }
        ossClient.shutdown();
        return list;
    }

    public boolean DeleteFileAvatar(String url) {

        /*地域节点*/
        String endpoint = OssUtil.END_POINT;
        /*用户身份ID*/
        String accessKeyId = OssUtil.ACCESS_KEY_ID;
        /*与用户身份ID配对的密钥*/
        String accessKeySecret = OssUtil.ACCESS_KEY_SECRET;
        /*存储库名*/
        String bucketName = OssUtil.BUCKET_NAME;

        /*创建OSSClient实例*/
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);


        // 使用URL类来解析URL
        String ObjectName = null;
        try {
            URL parsedUrl = new URL(url);

            // 获取路径部分，并去除可能的开头斜杠
            ObjectName = parsedUrl.getPath();

            if (ObjectName.startsWith("/")) {
                ObjectName = ObjectName.substring(1);
            }

            // 现在path包含了objectName，我们可以直接输出或处理它
            log.info("ObjectName:{}", ObjectName); // 输出: ObjectName: 20240530/1717030977127322.png
            ossClient.deleteObject(bucketName, ObjectName);
            // ossClient.shutdown();
        } catch (java.net.MalformedURLException e) {
            e.printStackTrace();
        }

        return ossClient.doesObjectExist(bucketName, ObjectName);
    }

    public void DeleteArrayFileAvatar(String[] urls) {

        /*地域节点*/
        String endpoint = OssUtil.END_POINT;
        /*用户身份ID*/
        String accessKeyId = OssUtil.ACCESS_KEY_ID;
        /*与用户身份ID配对的密钥*/
        String accessKeySecret = OssUtil.ACCESS_KEY_SECRET;
        /*存储库名*/
        String bucketName = OssUtil.BUCKET_NAME;

        /*创建OSSClient实例*/
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        // 使用URL类来解析URL

        for (String url : urls) {

            try {
                URL parsedUrl = new URL(url);

                // 获取路径部分，并去除可能的开头斜杠
                String ObjectName = parsedUrl.getPath();
                if (ObjectName.startsWith("/")) {
                    ObjectName = ObjectName.substring(1);
                }

                // 现在path包含了objectName，我们可以直接输出或处理它
                log.info("ObjectName:{}", ObjectName); // 输出: ObjectName: 20240530/1717030977127322.png
                ossClient.deleteObject(bucketName, ObjectName);

            } catch (java.net.MalformedURLException e) {
                e.printStackTrace();
            }
        }
    }
}
